package cn.edu.lingnan.servlet;

import cn.edu.lingnan.service.IStudentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@WebServlet("/user/ChangePasswordServlet")
public class ChangePasswordServlet extends HttpServlet {

    private IStudentService studentService = new IStudentService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException {
        request.setCharacterEncoding("UTF-8");

        // 获取当前用户ID（通过session获得）
        Integer studentId = (Integer) request.getSession().getAttribute("sid");
        if (studentId == null) {
            response.sendRedirect("/index.jsp");
            return;
        }

        // 获取表单数据
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");

        // 修改密码
        boolean isSuccess = studentService.changePassword(studentId, oldPassword, newPassword);
        if (isSuccess) {
            response.sendRedirect("/user/viewStu.jsp?message=Password changed successfully");
        } else {
            response.sendRedirect("/user/viewStu.jsp?message=Failed to change password");
        }
    }
}